<template>
  <div class="chat-area-container">
    <!-- 聊天头部 -->
    <div v-if="activeSession" class="toolbar" style="-webkit-app-region: drag">
      <div class="d-flex justify-content-between">
        <div class="flex">
          <div class="fs-medium text-bold">{{ activeSession.name }}</div>
          <div class="fs-small text-success ml-1 mt-1">在线</div>
        </div>
      </div>
      <div class="d-flex align-items-center" style="-webkit-app-region: no-drag">
        <button class="btn btn-text" title="更多操作" @click="handleMoreActions">⋯</button>
      </div>
    </div>

    <!-- 消息列表区域 -->
    <div v-if="activeSession" ref="messagesContainer" class="messages-container">
      <div class="d-flex flex-column">
        <div v-for="message in currentMessages" :key="message.id" class="mb-3">
          <div class="d-flex" :class="{ 'flex-row-reverse': isFromCurrentUser(message) }">
            <!-- 发送者头像 -->
            <div class="message-avatar">
              <Avatar
                :src="isFromCurrentUser(message) ? userStore.getUserAvatar : activeSession.avatar"
                :alt="isFromCurrentUser(message) ? '我' : activeSession.name"
                :username="
                  isFromCurrentUser(message) ? userStore.currentUser?.username : activeSession.name
                "
                :status="
                  isFromCurrentUser(message) ? userStore.currentUser?.status || 'offline' : 'online'
                "
                size="medium"
              />
            </div>

            <!-- 消息气泡 -->
            <div
              class="message-bubble"
              :class="[
                isFromCurrentUser(message) ? 'message-bubble-self' : 'message-bubble-other',
                {
                  'message-bubble--selected': messageSelection.isMessageSelected(message.id),
                  'message-bubble--selectable': messageSelection.state.isMultiSelectMode
                }
              ]"
              @click="handleMessageClick($event, message)"
              @dblclick="handleMessageDoubleClick"
              @contextmenu="handleMessageRightClick($event, message)"
            >
              <!-- 多选模式下的选择框 -->
              <div
                v-if="messageSelection.state.isMultiSelectMode"
                class="message-selection-indicator"
                :class="{
                  'message-selection-indicator--selected': messageSelection.isMessageSelected(
                    message.id
                  )
                }"
              >
                <span v-if="messageSelection.isMessageSelected(message.id)">✓</span>
              </div>

              {{ message.content }}
              <div class="message-time">
                {{ formatMessageTime(message.timestamp) }}
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <!-- 无会话时的占位 -->
    <div v-else class="flex-grow-1 d-flex align-items-center justify-content-center">
      <div class="text-center text-muted">
        <div class="fs-xxlarge mb-3 opacity-50">💬</div>
        <div class="fs-large">请选择一个聊天开始对话</div>
      </div>
    </div>
    <!-- 多选操作栏（当处于多选模式时显示） -->
    <MultiSelectToolbar
      v-if="messageSelection.state.isMultiSelectMode"
      :selected-count="messageSelection.selectedCount"
      :has-selected-messages="messageSelection.hasSelectedMessages"
      :total-count="currentMessages.length"
      @exit="handleExitMultiSelectMode"
      @confirm="handleConfirmSelection"
    />

    <!-- 消息输入区域（当不在多选模式时显示） -->
    <div v-if="activeSession && !messageSelection.state.isMultiSelectMode" class="input-container">
      <div class="input-wrapper">
        <!-- 输入框 -->
        <textarea
          v-model="messageInput"
          class="chat-input"
          placeholder="输入消息..."
          @keydown="handleKeydown"
          @input="handleInput"
        />

        <!-- 左上角工具按钮 -->
        <div class="tools-left">
          <InputToolbar
            @emoji-click="handleEmojiClick"
            @file-click="handleFileClick"
            @screenshot-click="handleScreenshotClick"
            @more-click="handleMoreClick"
          />
        </div>

        <!-- 右上角通话按钮 -->
        <div class="tools-right">
          <button class="tool-btn" title="语音通话" @click="handleVoiceCall">
            <Phone :size="16" />
          </button>
          <button class="tool-btn" title="视频通话" @click="handleVideoCall">
            <Video :size="16" />
          </button>
        </div>

        <!-- 右下角发送按钮 -->
        <div v-if="showSendButton" class="send-button-container">
          <button class="send-btn" @click="sendMessage">
            <Send :size="14" />
            发送
          </button>
        </div>
      </div>
    </div>
    <!-- 右键菜单组件 -->
    <ContextMenu />
  </div>
</template>

<script lang="ts" setup>
import { ref, computed, nextTick, onMounted, watch } from 'vue'
import { useChatStore } from '@/store/chat'
import { useUserStore } from '@/store/user'
import { Phone, Video, Send } from 'lucide-vue-next'
import ContextMenu from '@/libs/contextMenu/ContextMenu.vue'
import Avatar from '@/libs/Avatar/Avatar.vue'
import MultiSelectToolbar from './MultiSelectToolbar.vue'
import InputToolbar from './InputToolbar.vue'
import { useGlobalContextMenu } from '@/composables/useContextMenu'
import { useGlobalMessageSelection } from '@/composables/useMessageSelection'
import { formatMessageTime } from '@/utils/dateUtils'
import type { Message } from '@/store/chat'

const chatStore = useChatStore()
const userStore = useUserStore()

// 右键菜单和消息选择
const contextMenu = useGlobalContextMenu()
const messageSelection = useGlobalMessageSelection()

// 消息输入框内容
const messageInput = ref('')

// 消息列表容器引用
const messagesContainer = ref<HTMLElement>()

// 当前激活的会话
const activeSession = computed(() => chatStore.activeSession)

// 当前聊天消息列表
const currentMessages = computed(() => chatStore.currentMessages)

// 是否显示发送按钮
const showSendButton = computed(() => messageInput.value.trim().length > 0)

// 监听消息变化，自动滚动到底部
watch(
  currentMessages,
  () => {
    nextTick(() => {
      scrollToBottom()
    })
  },
  { deep: true }
)

// 滚动到消息列表底部
const scrollToBottom = (): void => {
  if (messagesContainer.value) {
    messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight
  }
}

// 发送消息
const sendMessage = (): void => {
  const content = messageInput.value.trim()
  if (!content || !activeSession.value) return

  chatStore.sendMessage(content, 'text')
  messageInput.value = ''
}

// 处理键盘事件
const handleKeydown = (event: KeyboardEvent): void => {
  if (event.key === 'Enter' && !event.shiftKey) {
    event.preventDefault()
    sendMessage()
  }
}

// 处理输入自动调整高度
const handleInput = (event: Event): void => {
  const target = event.target as HTMLTextAreaElement
  // 重置高度以获取正确的scrollHeight
  target.style.height = 'auto'
  // 设置新高度，最小1行，最大8行
  const lineHeight = 24 // 假设每行24px
  const minHeight = lineHeight
  const maxHeight = lineHeight * 8
  const scrollHeight = target.scrollHeight
  target.style.height = Math.min(Math.max(scrollHeight, minHeight), maxHeight) + 'px'
}

// 消息时间格式化已移至 utils/dateUtils.ts

// 判断消息是否来自当前用户
const isFromCurrentUser = (message: { senderId: string }): boolean => {
  return message.senderId === 'current-user'
}

// 简单的工具按钮处理
const handleEmojiClick = (): void => {
  console.log('点击表情')
}

const handleFileClick = (): void => {
  console.log('点击文件')
}

const handleScreenshotClick = (): void => {
  console.log('点击截图')
}

const handleMoreClick = (): void => {
  console.log('点击更多')
}

// 处理视频通话按钮点击
const handleVideoCall = (): void => {
  console.log('发起视频通话')
  // TODO: 发起视频通话
}

// 处理语音通话按钮点击
const handleVoiceCall = (): void => {
  console.log('发起语音通话')
  // TODO: 发起语音通话
}

// 处理更多操作按钮点击
const handleMoreActions = (): void => {
  console.log('点击更多操作')
  // TODO: 显示更多操作菜单
}

// 处理消息右键点击
const handleMessageRightClick = (event: MouseEvent, message: Message): void => {
  event.preventDefault()
  event.stopPropagation()
  contextMenu.showContextMenu(event, message.id, message)
}

// 处理消息点击（支持多选）
const handleMessageClick = (event: MouseEvent, message: Message): void => {
  if (messageSelection.state.isMultiSelectMode) {
    messageSelection.handleMessageClick(message.id, currentMessages.value, event)
  }
}

// 处理消息双击（退出多选模式）
const handleMessageDoubleClick = (): void => {
  if (messageSelection.state.isMultiSelectMode) {
    messageSelection.exitMultiSelectMode()
  }
}

// 处理退出多选模式
const handleExitMultiSelectMode = (): void => {
  messageSelection.exitMultiSelectMode()
  showToast('已退出多选模式')
}

// 处理确认选择
const handleConfirmSelection = (): void => {
  const selectedMessages = messageSelection.getSelectedMessages(currentMessages.value)

  // 确保至少选择了两条消息
  if (selectedMessages.length > 1) {
    // 这里可以执行批量操作，例如：
    // 1. 批量转发
    // 2. 批量删除
    // 3. 批量导出
    // 等等...
    showToast(`已确认选择 ${selectedMessages.length} 条消息`, 'success')

    // TODO: 在这里添加处理逻辑，例如打开一个操作菜单让用户选择要执行的批量操作
    console.log('已选择的消息:', selectedMessages)

    // 注意：这里我们不退出多选模式，只是确认选择
    // 如果需要自动退出多选模式，可以取消下面的注释
    // messageSelection.exitMultiSelectMode()
  }
}

// 显示提示消息
const showToast = (message: string, type: 'success' | 'error' | 'info' = 'success'): void => {
  // TODO: 实现Toast组件
  console.log(`[${type.toUpperCase()}] ${message}`)
}

// 组件挂载后滚动到底部
onMounted(() => {
  nextTick(() => {
    scrollToBottom()
  })
})
</script>

<style scoped>
/* 聊天区域主容器 - 使用flex布局防止滚动条问题 */
.chat-area-container {
  display: flex;
  flex-direction: column;
  height: 100%;
  min-height: 0; /* 重要：允许flex子项收缩 */
  overflow: hidden; /* 防止整体页面滚动 */
}

/* 聊天头部 - 固定高度，不允许收缩 */
.toolbar {
  flex-shrink: 0;
  height: 60px;
  padding: 0 16px;
  background: var(--background-color-primary);
  border-bottom: 1px solid var(--border-color-light);
  display: flex;
  align-items: center;
  justify-content: space-between;
}

/* 消息列表容器 - 占据剩余空间，独立滚动 */
.messages-container {
  flex: 1;
  overflow-y: auto; /* 只在消息区域滚动 */
  padding: 16px;
  min-height: 0; /* 重要：确保flex子项可以收缩 */
}

/* 输入区域容器 - 固定在底部，不允许收缩 */
.input-container {
  flex-shrink: 0;
  padding: 16px;
  background: var(--background-color-primary);
  border-top: 1px solid var(--border-color-light);
}
/* 消息气泡基础样式 */
.message-bubble {
  max-width: 400px;
  padding: var(--spacing-base) var(--spacing-medium);
  border-radius: var(--border-radius-large);
  word-wrap: break-word;
  word-break: break-word;
  position: relative;
  font-family: var(--font-family);
  font-size: var(--font-size-base);
  line-height: var(--line-height-normal);
  box-shadow: var(--shadow-small);
  transition: all var(--transition-duration) var(--transition-timing-function);
}

/* 自己发送的消息气泡 */
.message-bubble-self {
  background: var(--primary-color-light);
  color: var(--text-color-primary);
  margin-left: 60px;
  border: 1px solid var(--primary-color);
}

.message-bubble-self:hover {
  box-shadow: var(--shadow-medium);
  transform: translateY(-1px);
}

/* 对方发送的消息气泡 */
.message-bubble-other {
  background: var(--background-color-primary);
  color: var(--text-color-primary);
  margin-right: 60px;
  border: 1px solid var(--border-color-light);
}

.message-bubble-other:hover {
  box-shadow: var(--shadow-medium);
  transform: translateY(-1px);
  border-color: var(--border-color-normal);
}

/* 消息时间样式 */
.message-time {
  font-size: var(--font-size-small);
  color: var(--text-color-tertiary);
  margin-top: var(--spacing-mini);
  text-align: right;
  font-weight: var(--font-weight-regular);
}

/* 消息头像样式 */
.message-avatar {
  margin: 0 12px;
  flex-shrink: 0;
}

/* 输入框样式 - 使用CSS框架 */
.input-wrapper {
  position: relative;
  border-radius: var(--border-radius-large);
  overflow: hidden;
  box-shadow: var(--shadow-small);
  transition: all var(--transition-duration) var(--transition-timing-function);
}

.input-wrapper:hover {
  box-shadow: var(--shadow-medium);
}

.input-wrapper:focus-within {
  box-shadow: 0 0 0 2px var(--primary-color-light);
  border-color: var(--primary-color);
}

.chat-input {
  width: 100%;
  min-height: 120px;
  max-height: 200px;
  padding: var(--spacing-xxlarge) var(--spacing-xxlarge) var(--spacing-medium) var(--spacing-medium);
  border: 1px solid var(--border-color-normal);
  border-radius: var(--border-radius-large);
  font-family: var(--font-family);
  font-size: var(--font-size-base);
  line-height: var(--line-height-normal);
  resize: none;
  outline: none;
  background: var(--background-color-primary);
  color: var(--text-color-primary);
  transition: all var(--transition-duration) var(--transition-timing-function);
}

.chat-input:focus {
  border-color: var(--primary-color);
  box-shadow: 0 0 0 2px var(--primary-color-light);
}

.chat-input::placeholder {
  color: var(--text-color-tertiary);
  font-weight: var(--font-weight-regular);
}

/* 左上角工具按钮 */
.tools-left {
  position: absolute;
  top: var(--spacing-small);
  left: var(--spacing-small);
  display: flex;
  gap: var(--spacing-mini);
}

/* 右上角工具按钮 */
.tools-right {
  position: absolute;
  top: var(--spacing-small);
  right: var(--spacing-small);
  display: flex;
  gap: var(--spacing-mini);
}

/* 工具按钮样式 */
.tool-btn {
  width: 32px;
  height: 32px;
  border: none;
  background: transparent;
  cursor: pointer;
  border-radius: var(--border-radius-base);
  display: flex;
  align-items: center;
  justify-content: center;
  color: var(--text-color-secondary);
  transition: all var(--transition-duration) var(--transition-timing-function);
}

.tool-btn:hover {
  background-color: var(--background-color-tertiary);
  color: var(--text-color-primary);
  transform: scale(1.05);
}

.tool-btn:active {
  transform: scale(0.95);
}

/* 右下角发送按钮容器 */
.send-button-container {
  position: absolute;
  bottom: var(--spacing-small);
  right: var(--spacing-small);
  display: flex;
  align-items: center;
}

.send-btn {
  background: var(--primary-color);
  color: white;
  border: none;
  padding: var(--spacing-mini) var(--spacing-small);
  border-radius: var(--border-radius-large);
  font-family: var(--font-family);
  font-size: var(--font-size-small);
  font-weight: var(--font-weight-medium);
  cursor: pointer;
  height: 32px;
  display: flex;
  align-items: center;
  gap: var(--spacing-mini);
  transition: all var(--transition-duration) var(--transition-timing-function);
  box-shadow: var(--shadow-small);
}

.send-btn:hover {
  background: var(--primary-color-hover);
  box-shadow: var(--shadow-medium);
  transform: translateY(-1px);
}

.send-btn:active {
  transform: translateY(0);
  box-shadow: var(--shadow-small);
}

/* 自定义滚动条 */
.messages-container::-webkit-scrollbar {
  width: 6px;
}

.messages-container::-webkit-scrollbar-track {
  background: transparent;
}

.messages-container::-webkit-scrollbar-thumb {
  background: var(--border-color-normal);
  border-radius: var(--border-radius-small);
}

.messages-container::-webkit-scrollbar-thumb:hover {
  background: var(--text-color-tertiary);
}

.chat-input::-webkit-scrollbar {
  width: 4px;
}

.chat-input::-webkit-scrollbar-track {
  background: transparent;
}

.chat-input::-webkit-scrollbar-thumb {
  background: var(--border-color-light);
  border-radius: var(--border-radius-small);
}

.chat-input::-webkit-scrollbar-thumb:hover {
  background: var(--border-color-normal);
}

/* ===== 右键菜单和消息选择样式 ===== */

/* 可选择的消息气泡 */
.message-bubble--selectable {
  cursor: pointer;
  user-select: none;
  position: relative;
  transition: all var(--transition-duration) var(--transition-timing-function);
}

.message-bubble--selectable:hover {
  transform: translateY(-2px);
  box-shadow: var(--shadow-medium);
}

/* 选中状态的消息气泡 */
.message-bubble--selected {
  border: 2px solid var(--primary-color) !important;
  box-shadow: 0 0 0 2px var(--primary-color-light);
  transform: translateY(-1px);
}

.message-bubble--selected.message-bubble-self {
  background: var(--primary-color-light) !important;
  border-color: var(--primary-color) !important;
}

.message-bubble--selected.message-bubble-other {
  background: var(--background-color-tertiary) !important;
  border-color: var(--primary-color) !important;
}

/* 消息选择指示器 */
.message-selection-indicator {
  position: absolute;
  top: -8px;
  right: -8px;
  width: 20px;
  height: 20px;
  border-radius: var(--border-radius-circle);
  background: var(--background-color-primary);
  border: 2px solid var(--border-color-normal);
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: var(--font-size-small);
  font-weight: var(--font-weight-medium);
  transition: all var(--transition-duration) var(--transition-timing-function);
  z-index: 10;
  box-shadow: var(--shadow-small);
}

.message-selection-indicator:hover {
  transform: scale(1.1);
  box-shadow: var(--shadow-medium);
}

.message-selection-indicator--selected {
  background: var(--primary-color);
  border-color: var(--primary-color);
  color: white;
  box-shadow: var(--shadow-medium);
}

/* 多选模式下的消息气泡动画 */
.message-bubble--selectable {
  transition: all var(--transition-duration) var(--transition-timing-function);
}

/* 右键菜单相关的过渡动画 */
.message-bubble {
  transition: all var(--transition-duration) var(--transition-timing-function);
}

.message-bubble:hover {
  filter: brightness(0.98);
}

/* 深色主题适配 */
[data-theme='dark'] .message-bubble--selected.message-bubble-self {
  background: #2d5016;
}

[data-theme='dark'] .message-bubble--selected.message-bubble-other {
  background: #1a2332;
}

[data-theme='dark'] .message-selection-indicator {
  background: var(--theme-bg-secondary);
  border-color: var(--theme-border);
}

[data-theme='dark'] .message-selection-indicator--selected {
  background: var(--theme-primary);
  border-color: var(--theme-primary);
}

/* 深色主题工具按钮 */
[data-theme='dark'] .tool-btn {
  color: var(--text-color-tertiary);
}

[data-theme='dark'] .tool-btn:hover {
  background-color: var(--background-color-secondary);
  color: var(--text-color-primary);
}
</style>
